package com.xs.tool;

import com.xs.tool.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Util {
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class Test{
        private String name;
        private Integer age;
        private String sex;
    }

    public static <T> T obtainUpdateJson(T po, T update) {
        if (po == null || update == null || po.getClass() != update.getClass()) {
            throw new RuntimeException("po 和 addValue 类型不一致或为空");
        }

        Map<String, Object> result = new HashMap<>();
        Class<?> clazz = po.getClass();

        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            try {
                Object poValue = field.get(po);
                Object updateValue = field.get(update);

                if (!Objects.equals(poValue, updateValue)) {
                    result.put(field.getName(), updateValue);
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException("字段访问失败: " + field.getName(), e);
            }
        }

        return (T) BeanUtil.toBean(result, clazz);
    }

    public static void main(String[] args) {
        //测试
        TestBean po = new TestBean();
        po.setField1("value1");
        po.setField2(100);

        TestBean update = new TestBean();
        update.setField1("updated_value1");
        update.setField2(100);

        TestBean result = Util.obtainUpdateJson(po, update);
        System.out.println("差异字段: " + result);
    }

    // 用于测试的简单POJO类
    static class TestBean {
        private String field1;
        private int field2;

        public String getField1() {
            return field1;
        }

        public void setField1(String field1) {
            this.field1 = field1;
        }

        public int getField2() {
            return field2;
        }

        public void setField2(int field2) {
            this.field2 = field2;
        }
    }
}
